package com.quectel.cms.controller.partyeducationtraining;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.partyeducationtraining.TrainingConstants;
import com.quectel.constant.core.partyeducationtraining.TrainingItemConstants;
import com.quectel.constant.global.FileTypeSuffix;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingItemDto;
import com.quectel.core.module.partyeducationtraining.dto.ref.TrainingItemRefPersonDto;
import com.quectel.core.module.partyeducationtraining.service.TrainingItemPersonService;
import com.quectel.core.module.partyeducationtraining.service.TrainingItemService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:40
 */
@RestController
@RequestMapping("trainingItem")
@Tag(name = "TrainingItemController", description = "培训课程项表相关api")
public class TrainingItemController extends BaseController {

    @DubboReference
    private TrainingItemService trainingItemService;
    @DubboReference
    private TrainingItemPersonService trainingItemPersonService;
    @DubboReference
    private TrainingService trainingService;

    /**
     * 导出课时学习进度列表
     */
    @GetMapping("exportPersonExcel")
    @RequirePermissions(values = "trainingItem:export")
    @Operation(summary = "导出课时学习列表")
    public void exportPersonExcel(@RequestParam Map<String, Object> params,
                                  HttpServletResponse resp) {
        //查询列表数据
        Request request = Request.configParamsNotPage(params)
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getName))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getMobile));

        super.fillAuthorityData(params);
        List<TrainingItemRefPersonDto> list = new ArrayList<>();
        int pageNo = 0;
        params.put("limit", 10000);
        while (true) {
            params.put("offset", pageNo++ * 10000);
            List<TrainingItemRefPersonDto> trainingCommentDtos = trainingItemPersonService.queryPersonList(params);
            if (CollectionUtils.isEmpty(trainingCommentDtos)) {
                break;
            }
            list.addAll(trainingCommentDtos);

        }
        String[] headers = new String[]{"课时名称", "姓名", "联系电话", "所属部门", "状态", "开始时间", "完成时间"};
        List<String[]> dataList = new ArrayList<>();
        for (TrainingItemRefPersonDto data : list) {
            String[] item = new String[headers.length];
            item[0] = data.getTrainingItemName();
            item[1] = data.getName();
            item[2] = data.getMobile();
            item[3] = data.getParty() == null ? "" : data.getParty().getName();
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.TRAINING_ITEM_STUDY_STATUS, String.valueOf(data.getStudyStatus()));
            item[5] = DateUtils.format(data.getStartTime(), DateUtils.FormatType.COMMON);
            item[6] = DateUtils.format(data.getEndTime(), DateUtils.FormatType.COMMON);
            dataList.add(item);
        }
        POIUtils.exportExcel(resp, "课时学习情况", headers, dataList, "课时学习情况");

    }

    /**
     * 课时已培训人员列表
     */
    @GetMapping("itemPersonList")
    @RequirePermissions(values = "trainingItem:list")
    @Operation(summary = "课时已培训人员列表")
    public Response<Page<TrainingItemRefPersonDto>> itemPersonList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "课时id") @RequestParam Long trainingItemId
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getName))
                .like(LambdaUtil.getFieldName(TrainingItemRefPersonDto::getMobile));

        super.fillAuthorityData(request.getParams());
        int total = trainingItemPersonService.queryPersonTotal(request.getParams());

        List<TrainingItemRefPersonDto> list = null;
        if (total > 0) {
            list = trainingItemPersonService.queryPersonList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<TrainingItemRefPersonDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<TrainingItemRefPersonDto>>ok().wrap(page);
    }

    /**
     * 列表
     */
    @GetMapping("list")
    @RequirePermissions(values = "trainingItem:list")
    @Operation(summary = "分页列表")
    public Response<Page<TrainingItemDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest))
                .like(LambdaUtil.getFieldName(TrainingItemDto::getName));

        super.fillAuthorityData(request.getParams());
        int total = trainingItemService.queryTotal(request.getParams());

        List<TrainingItemDto> list = null;
        if (total > 0) {
            list = trainingItemService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<TrainingItemDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<TrainingItemDto>>ok().wrap(page);
    }


    /**
     * 编辑反显查询
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "trainingItem:edit")
    @Operation(summary = "查询单条记录")
    public Response<TrainingItemDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingItemDto trainingItemDto = trainingItemService.selectById(id);

        return Response.<TrainingItemDto>ok().wrap((trainingItemDto));
    }

    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "trainingItem:info")
    @Operation(summary = "查询单条记录")
    public Response<TrainingItemDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (trainingItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        TrainingItemDto trainingItemDto = trainingItemService.selectById(id);

        return Response.<TrainingItemDto>ok().wrap((trainingItemDto));
    }

    /**
     * 课时操作校验
     *
     * @param trainingId
     * @return
     */
    private boolean forbidOperate(Long trainingId) {
        // 课时操作校验 已推送或到达推送时间 不允许操作
        long currentTimeMillis = System.currentTimeMillis();
        TrainingDto dbTrainingDto = trainingService.selectById(trainingId);
        if (TrainingConstants.PushStatusEnum.PUSHED.getPushStatus().equals(dbTrainingDto.getPushStatus())
                || currentTimeMillis > DateUtil.offsetMinute(dbTrainingDto.getStartTime(), -1 * (dbTrainingDto.getPushBeforeLearnMins() == null
                ? 0 : dbTrainingDto.getPushBeforeLearnMins())).getTime()) {
            return true;
        }
        return false;
    }

    /**
     * 保存
     */
    @PostMapping("save")
    @RequirePermissions(values = "trainingItem:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated TrainingItemDto trainingItemDto) {
        if (forbidOperate(trainingItemDto.getTrainingId())) {
            return Response.error("仅未开始的课程允许添加！");
        }

        if (TrainingItemConstants.FileType.PDF.getFileType().equals(trainingItemDto.getFileType())) {
            if (!trainingItemDto.getFileUrl().toLowerCase().endsWith(FileTypeSuffix.PDF)) {
                return Response.error("文件类型不符");
            }
        } else if (TrainingItemConstants.FileType.MP4.getFileType().equals(trainingItemDto.getFileType())) {
            if (!trainingItemDto.getFileUrl().toLowerCase().endsWith(FileTypeSuffix.MP4)) {
                return Response.error("文件类型不符");
            }
        }

        //填充基础数据
        fillSaveCommonData(trainingItemDto);

        trainingItemService.save(trainingItemDto);

        return Response.ok();
    }

    /**
     * 修改
     */
    @PostMapping("update")
    @RequirePermissions(values = "trainingItem:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated TrainingItemDto trainingItemDto) {
        if (forbidOperate(trainingItemDto.getTrainingId())) {
            return Response.error("仅未开始的课程允许编辑！");
        }

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(trainingItemDto.getId()));
        if (trainingItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(trainingItemDto);

        trainingItemService.updateById(trainingItemDto);

        return Response.ok();
    }

    /**
     * 删除
     */
    @PostMapping("delete")
    @RequirePermissions(values = "trainingItem:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (trainingItemService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }

            TrainingItemDto trainingItemDto = trainingItemService.selectCacheById(id);
            if (forbidOperate(trainingItemDto.getTrainingId())) {
                return Response.error("仅未开始的课程允许删除！");
            }
        }

        trainingItemService.deleteBatch(ids);

        return Response.ok();
    }
}
